package com.thwj.framework.config.wx;

import com.thwj.framework.config.properties.WxMpProperties;
import com.thwj.project.wechat_subscribe.handler.LogHandler;
import com.thwj.project.wechat_subscribe.handler.SubscribeHandler;
import com.thwj.project.wechat_subscribe.handler.UnsubscribeHandler;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.util.Pool;

/**
 * wechat mp configuration
 *
 * @author Binary Wang(https://github.com/binarywang)
 */
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WxMpConfiguration {

    @Autowired
    private WxMpProperties wxMpProperties;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    UnsubscribeHandler unsubscribeHandler;
    @Autowired
    SubscribeHandler subscribeHandler;
    @Autowired
    LogHandler logHandler;


    @Bean
    public WxMpService wxMpService() {
        WxMpService wxService = new WxMpServiceImpl();
        WxMpJedisSentinelPoolConfigImpl config = getMPConfig(jedisPool, wxMpProperties.getAppid(), wxMpProperties.getSecret(), wxMpProperties.getToken(), wxMpProperties.getAesKey());
        wxService.setWxMpConfigStorage(config);
        return wxService;
    }


    @Bean
    public WxMpMessageRouter messageMpRouter(WxMpService wxMpService) {
        final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService);
        // 记录所有事件的日志
        newRouter.rule().handler(this.logHandler).next();
        // 关注事件
        newRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT)
                .event(WxConsts.EventType.SUBSCRIBE).handler(subscribeHandler)
                .end();

        // 取消关注事件
        newRouter.rule().async(false).msgType(WxConsts.XmlMsgType.EVENT)
                .event(WxConsts.EventType.UNSUBSCRIBE).handler(unsubscribeHandler)
                .end();

        return newRouter;
    }
    private WxMpJedisSentinelPoolConfigImpl getMPConfig(Pool<Jedis> jedisPool, String appid, String secret, String token, String aesKey) {
        WxMpJedisSentinelPoolConfigImpl config = new WxMpJedisSentinelPoolConfigImpl(jedisPool);
        config.setAppId(appid);
        config.setSecret(secret);
        config.setToken(token);
        config.setAesKey(aesKey);
        return config;
    }
}
